<!-- 电子签章自研/非自研代办主页面入口 -->
<template>
  <div>
    <el-header height="36px">
      <header-title :title="headerTitle" />
    </el-header>
    <component
      :is="page"
      v-for="page in pageSetting"
      ref="myTables"
      :key="page"
      :process-inst-id="workDetail.processInstID"
    />
    <FooterButton
      v-if="queryParams.type === 'todo'"
      :btn-list="btnOption"
      class="btn-init"
      @handleBtn="handleClick"
    />
    <!-- 下一步  -->
    <next-page
      v-if="nextPageVisible"
      ref="nextPage"
      :visible.sync="nextPageVisible"
      :activity-inst-id="workDetail.activityInstID"
      :process-inst-id="workDetail.processInstID"
      :activity-def-id="workDetail.activityDefID"
      :process-def-name="workDetail.processDefName"
      :user-ids="userIds"
      @doNextEntity="nextPageRes"
    />
    <!--  回退 -->
    <Back-page
      v-if="backPageVisible"
      ref="backPage"
      :visible.sync="backPageVisible"
      :process-inst-id="workDetail.processInstID"
      :act-inset-id="workDetail.actInsetId"
      :route="routeShow"
      @doReturn="backPageRes"
    />
    <!-- 转派 -->
    <TransferPage
      v-if="transferPageVisible"
      :visible.sync="transferPageVisible"
      :process-inst-id="workDetail.processInstID"
      :org-id="_userInfo.parentWorkGroupId"
      :org-code="workDetail.orgCode"
      @redeployEntity="redeployEntity"
    />
  </div>
</template>

<script>
import HeaderTitle from '@/components/basic/HeaderTitle'
import BasicDataInfo from './components/BasicDataInfo.vue'
import TaskBasicInfo from './components/TaskBasicInfo.vue'
import JnTaskDetail from '@/components/jn/JnTaskDetail.vue'
import AttachSignInfo from '@/views/attachManagement/electronicSign/attachSignInfo/attachSignInfo.vue'
import BackPage from '@/components/nextPerson/BackPage.vue'
import NextPage from '@/components/nextPerson/NextPage.vue'
import TransferPage from '@/components/nextPerson/ReassignPageNew.vue'
import FooterButton from '@/components/basic/TPageBtn.vue'
import { pageSettings, ENUM_TYPE_STATUS, CONSOLE_MESSAGE } from './setting'
import { clonePage } from '@/utils'
import { getWFWorkItem } from '@/api/actualBudget/index'
import { queryBasicTask } from '@/api/attachManagement/electronicSign/electronicSignature'
import {
    confirmcDoNextFlow,
    confirmcDoBackFlow,
    confirmcDoReassignFlow,
    saveSingareTableInfo,
    doNextFlowCheck
} from '@/api/electSingnare/index'
export default {
    name: 'ElectronicSignature',
    components: {
        BasicDataInfo,
        TaskBasicInfo,
        JnTaskDetail,
        AttachSignInfo,
        NextPage,
        FooterButton,
        BackPage,
        TransferPage,
        HeaderTitle
    },
    provide() {
        return {
            workDetail: () => this.workDetail
        }
    },
    data() {
        return {
            pageSettings, // 路由配置
            pageSetting: [], // 页面配置
            // 工作项信息
            workDetail: {},
            nextPageVisible: false,
            backPageVisible: false,
            transferPageVisible: false,
            btnOption: [],
            userIds: '',
            headerTitle: '',
            taskInfoObj: {},
            routeShow: '',
            _userInfo: {}
        }
    },
    computed: {
        queryParams() {
            return this.$route.query
        }
    },
    created() {
        this.getWorkItemInfo()
        this._userInfo = JSON.parse(sessionStorage.getItem('SET_LOGINDATA')) || {}
    },
    methods: {
      async  getHeadreTitle() {
            const params = {
                taskId: this.workDetail?.bizObject?.bizSeq,
                workItemId: this.workDetail?.bizObject?.nodeCode === 'electronicSeal_301' ? this.workDetail.workItemID : null,
                pageNum: 1,
                pageSize: 10
            }
            const { code, data } = await queryBasicTask(params)
            if (+code === 200) {
                this.headerTitle = data.records[0].taskName
                this.taskInfoObj = data.records[0]
                console.log(this.taskInfoObj, CONSOLE_MESSAGE, '任务详情')
            }
        },
        // 初始化获取工作项信息
        async getWorkItemInfo() {
            const { code, data } = await getWFWorkItem({
                workItemId: this.queryParams.workItemId
            })
            console.log(CONSOLE_MESSAGE, data, '工作项信息')
            if (+code === 200) {
                const { bizObject } = data
                this.routeShow = bizObject.bizState === 'WD2' ? 'start' : ''
                this.workDetail = data
                this.btnOption = JSON.parse(bizObject?.buttonConfig) || []
                this.getHeadreTitle()
                this.isSelfResearchAgency()
            }
        },
        // 判断是否自研项目配置页面
        isSelfResearchAgency() {
            // 自研/非自研
            const { processDefName } = this.workDetail
            this.pageSetting =
                processDefName === ENUM_TYPE_STATUS
                    ? pageSettings['NonSelfResearchAgency']
                    : pageSettings['SelfResearchAgency']
        },
        handleClick(fun) {
            this[fun]()
        },
        // save
        async save(type = true) {
            console.log(CONSOLE_MESSAGE, this.$refs.myTables[1].addData, '保存数据', this.$refs.myTables[1].tableData)
            const { processDefName } = this.workDetail
            // 非自研不保存
            if (processDefName === ENUM_TYPE_STATUS) {
                return this.$message('没有要保存的内容!')
            }
            // 调用真实保存接口
            await this.reallySave(type)
        },
        // 真保存
        async reallySave(type) {
            // 调接口进行保存将自己手动添加的showSelect属性删掉  保存成功以后清空手动添加的数据
            const copyData = JSON.parse(JSON.stringify(this.$refs?.myTables[1]?.tableData)) || []
            copyData.forEach(item => {
                delete item.showSelect
            })
            // 保存的数据
            const filterList = copyData.filter((item) => {
                return Object.values(item).some(value => {
                    // 检查值是否不是以下“空”值之一：null, undefined, 空字符串
                    return value !== null && value !== undefined && value !== ''
                })
            })
            const { taskId, taskQuarter, taskYear } = this.taskInfoObj
            // 保存的数据需要加上taskId taskQuarter taskYear
            const resultList = filterList.map(item => {
                return {
                    ...item,
                    taskId,
                    taskQuarter,
                    taskYear
                }
            })
            if (resultList.length < 1) {
                if (type) {
                    this.$message('没有要保存的内容!')
                }
                return
            }
            const { code } = await saveSingareTableInfo(resultList, 0)
            if (+code === 200) {
                this.$refs.myTables[1].addData = []
                this.$refs.myTables[1]?.refreshTableData()
                if (type) {
                    this.$message.success('保存成功！')
                }
            }
        },
        // donext
        async doNext() {
            if (this.workDetail.processDefName !== ENUM_TYPE_STATUS && this.workDetail.processDefName !== 'chinatower.pms.bpm.wd.manager_electronicSeal') {
                // 下一步之前必须先保存数据 判断是否存在未保存的数据 如果有请先保存
                await this.save(false)
            }
            // 进行强校验
            const { code, message } = await this.checkDoNext()
            if (+code !== 200) {
                return this.$message.error(message)
            }
            // userIds 需要手动写处理人
            this.userIds = this.workDetail?.bizObject?.bizJson === 'WD402' ? 'yezhen' : ''
            // 节点1 不进行选人的逻辑
            if (this.workDetail.bizObject.nodeCode === 'electronicSeal_101') {
                const params = {
                    workItemId: this.workDetail.workItemID,
                    bizSeq: this.workDetail.bizObject.bizSeq,
                    activityDefId: this.workDetail.activityDefID // 当前节点
                }
                this.doNextConfirm(params, true)
                return
            }
            this.nextPageVisible = true
        },
        async checkDoNext() {
            const { taskId, taskQuarter, taskYear } = this.taskInfoObj
            const params = {
                taskQuarter,
                taskYear,
                taskId: this.workDetail.bizObject.bizSeq,
                nodeId: this.workDetail.bizObject.nodeCode, // 当前节点
                workItemId: this.workDetail.workItemID
            }
            const { code, message } = await doNextFlowCheck(params)
            return {
                code,
                message
            }
        },
        // 回退
        doBack() {
            this.backPageVisible = true
        },
        // 转派
        doReassign() {
            this.transferPageVisible = true
        },
        // 关闭
        close() {
            clonePage()
        },
        // 下一步回调函数
        nextPageRes(item) {
            const params = {
                workItemId: this.workDetail.workItemID,
                userIds: item.empId,
                bizSeq: this.workDetail.bizObject.bizSeq,
                opinion: item.opinion,
                nextSceneId: item.nextSceneId, // 先不传
                nodeId: item.nodeId,
                detailId: item.detailId, // 先不传
                activityDefId: item.actDefId, // 当前节点
                finish: item.finish, // 当前节点
                templateId: item.nTemplateId
            }
            this.doNextConfirm(params)
        },
        async doNextConfirm(params, type = false) {
            const { code } = await confirmcDoNextFlow(params)
            if (+code === 200) {
                if (type) {
                    this.$message.success(
                        '当前数据信息已汇总下发到对应服务商人员代办下！'
                    )
                } else {
                    this.$message.success('操作成功')
                }
                this.close()
            }
        },
        // 回退回调函数
        async backPageRes(item) {
            // doBack
            const params = {
                workItemId: this.workDetail.workItemID,
                opinion: item.opinion,
                bizSeq: this.workDetail.bizObject.bizSeq,
                nextActDefId: item.nodeId, // 暂定
                detailId: item.detailId
            }
            const { code } = await confirmcDoBackFlow(params)
            if (+code === 200) {
                this.$message.success('操作成功')
                this.close()
            }
        },
        // 转派回调函数
        async redeployEntity(item) {
            const params = {
                workItemId: this.workDetail.workItemID,
                userIds: item.empId,
                opinion: item.opinion,
                bizSeq: this.workDetail?.bizObject?.bizSeq,
                dealType: 'reassign'
            }
            const { code } = await confirmcDoReassignFlow(params)
            if (+code === 200) {
                this.$message.success('操作成功')
                this.close()
            }
        }
    }
}
</script>
<style lang="scss" scoped></style>
